/*
 * Copyright (c) 2009 Sun Microsystems, Inc.
 * Copyright (c) 2011 Oracle Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 **/

package com.sun.spot.wot.gateway;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import com.sun.spot.wot.http.HttpRequest;
import com.sun.spot.wot.http.HttpResponse;

/**
 *
 * @author vgupta
 */
class RequestQueue {
    private static Random rand = new Random();
    HashMap requestMap = new HashMap();
    Queue requests = new LinkedList();
    int pending = 0;
    int completed = 0;

    private String generateId() {
        long val = rand.nextLong();

        if (val < 0) val = 0L - val;
        // XXX: Make sure this is really unique (add device Id and/or time)
        return "" + val;
    }

    synchronized String insertRequest(HttpRequest req) {
        String id = generateId();
        RequestQueueEntry rqe = new RequestQueueEntry(id,
                System.currentTimeMillis(), req);

        if (requests.offer(rqe)) {
            requestMap.put(id, rqe);
            pending++;
            return id;
        }

        return null;
    }

    synchronized void markComplete(String id, HttpResponse res) {
        RequestQueueEntry rqe = (RequestQueueEntry) requestMap.get(id);
        if (rqe != null) {
//            System.out.println("Marking request " + id + " completed ...");
            rqe.setResponse(res);
            rqe.setRequestCompletionTime(System.currentTimeMillis());
            pending--;
            completed++;
        } else {
            System.err.println("Request " + id + " not found ...");
        }
    }

    synchronized RequestQueueEntry findRequest(String id) {
       RequestQueueEntry rqe = (RequestQueueEntry) requestMap.get(id);
       return rqe;
    }

    synchronized RequestQueueEntry removeRequest(String id) {
        RequestQueueEntry rqe = (RequestQueueEntry) requestMap.get(id);
        if (rqe != null) {
            if (requests.poll() != null) {
                if (rqe.getResponse() == null) {
                    pending--;
                } else {
                    completed--;
                }
                requestMap.remove(id);
            }
        }

        return rqe;
    }

    synchronized public String getSummary() {
        StringBuffer sb = new StringBuffer();
        int size = requests.size();
        if (size == 0)
            sb.append("empty");
        else {
            sb.append(size + " entries" + "<br/>");            
            sb.append("Pending: " + pending + "<br/>");
            sb.append("Completed: " + completed);
        }

        return sb.toString();
    }

    synchronized public String toString() {
        StringBuffer sb = new StringBuffer();

        Iterator i = requests.iterator();
        while (i.hasNext()) {
            RequestQueueEntry rqe = (RequestQueueEntry) i.next();
            sb.append(rqe.toString());
        }

        return sb.toString();
    }

    synchronized RequestQueueEntry getNextPendingEntry() {        
        Iterator i = requests.iterator();
        while (i.hasNext()) {
            RequestQueueEntry result = (RequestQueueEntry) i.next();
            if (result.getResponse() == null) return result;
        }

        //System.out.println("getNextpending returned null");
        return null;
    }

}
